const { StoredWine, User } = require('../models');
const { Op } = require('sequelize');

// 创建寄存酒记录
exports.createWine = async (req, res, next) => {
  try {
    const { userId, wineName, wineType, quantity, unit, storageDate, notes } = req.body;

    // 验证必填字段
    if (!userId || !wineName || !wineType || !quantity || !storageDate) {
      return res.status(400).json({
        success: false,
        message: '请提供完整的寄存信息'
      });
    }

    // 验证用户是否存在
    const user = await User.findByPk(userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    const wine = await StoredWine.create({
      userId,
      wineName,
      wineType,
      quantity,
      unit: unit || '瓶',
      storageDate,
      notes,
      status: 'stored'
    });

    res.status(201).json({
      success: true,
      message: '寄存成功',
      data: wine
    });
  } catch (error) {
    next(error);
  }
};

// 获取寄存酒列表
exports.getWines = async (req, res, next) => {
  try {
    const { page = 1, limit = 10, status, userId, search } = req.query;
    const offset = (page - 1) * limit;

    const where = {};
    if (status) where.status = status;
    if (userId) where.userId = userId;
    if (search) {
      where[Op.or] = [
        { wineName: { [Op.like]: `%${search}%` } },
        { wineType: { [Op.like]: `%${search}%` } }
      ];
    }

    const { count, rows: wines } = await StoredWine.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'name', 'phone']
        }
      ],
      limit: parseInt(limit),
      offset: parseInt(offset),
      order: [['createdAt', 'DESC']]
    });

    res.json({
      success: true,
      data: {
        wines,
        pagination: {
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          totalPages: Math.ceil(count / limit)
        }
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取单条寄存酒记录
exports.getWineById = async (req, res, next) => {
  try {
    const { id } = req.params;

    const wine = await StoredWine.findByPk(id, {
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'name', 'phone']
        }
      ]
    });

    if (!wine) {
      return res.status(404).json({
        success: false,
        message: '寄存记录不存在'
      });
    }

    res.json({
      success: true,
      data: wine
    });
  } catch (error) {
    next(error);
  }
};

// 更新寄存酒信息
exports.updateWine = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { wineName, wineType, quantity, unit, notes } = req.body;

    const wine = await StoredWine.findByPk(id);

    if (!wine) {
      return res.status(404).json({
        success: false,
        message: '寄存记录不存在'
      });
    }

    if (wineName) wine.wineName = wineName;
    if (wineType) wine.wineType = wineType;
    if (quantity !== undefined) wine.quantity = quantity;
    if (unit) wine.unit = unit;
    if (notes !== undefined) wine.notes = notes;

    await wine.save();

    res.json({
      success: true,
      message: '更新成功',
      data: wine
    });
  } catch (error) {
    next(error);
  }
};

// 取酒操作
exports.takeWine = async (req, res, next) => {
  try {
    const { id } = req.params;

    const wine = await StoredWine.findByPk(id);

    if (!wine) {
      return res.status(404).json({
        success: false,
        message: '寄存记录不存在'
      });
    }

    if (wine.status === 'taken') {
      return res.status(400).json({
        success: false,
        message: '该酒已被取出'
      });
    }

    wine.status = 'taken';
    await wine.save();

    res.json({
      success: true,
      message: '取酒成功',
      data: wine
    });
  } catch (error) {
    next(error);
  }
};

// 删除寄存酒记录
exports.deleteWine = async (req, res, next) => {
  try {
    const { id } = req.params;

    const wine = await StoredWine.findByPk(id);

    if (!wine) {
      return res.status(404).json({
        success: false,
        message: '寄存记录不存在'
      });
    }

    await wine.destroy();

    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    next(error);
  }
};

// 获取用户寄存酒列表
exports.getUserWines = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const { status } = req.query;

    const where = { userId };
    if (status) where.status = status;

    const wines = await StoredWine.findAll({
      where,
      order: [['createdAt', 'DESC']]
    });

    res.json({
      success: true,
      data: wines
    });
  } catch (error) {
    next(error);
  }
};
